package cn.bonoon.kernel.io.redirect;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;

import cn.bonoon.kernel.io.FileManager;
import cn.bonoon.kernel.io.HttpStorageFile;
import cn.bonoon.kernel.io.authority.AbstractAuthorityRedirect;
import cn.bonoon.util.PathUtil;

public class Redirect2RemoteServer extends AbstractAuthorityRedirect implements FileRedirectHandler{

	private String serverHost;

	private String fileLoadUrl = FileManager.OPEN_LOAD_URL;
	private String fileOpenUrl = FileManager.OPEN_OPEN_URL;
	
	@Override
	public void redirectOpen(HttpStorageFile file) throws Exception {
		redirect(fileOpenUrl, file);
	}
	
	@Override
	public void redirectLoad(HttpStorageFile file) throws Exception {
		redirect(fileLoadUrl, file);
	}
	
	private String dateFormatString = "yyyyMMddHHmmss";
	
	private SimpleDateFormat dateFormat;

	//return Base64.encodeBase64String(path.getBytes(charsetCode));

	private String charsetCode = "UTF-8";
	
	private void redirect(String url, HttpStorageFile file) throws Exception {
		 
		if(null == dateFormat) dateFormat = new SimpleDateFormat(dateFormatString);
		String timestamp = dateFormat.format(new Date());
		String targetUrl = catalog + ":" + file.getFilepath();
		String secret = combineSecret(timestamp, targetUrl);
		targetUrl = Base64.encodeBase64String(targetUrl.getBytes(charsetCode));
		
		String remoteUrl = PathUtil.path(serverHost, url);
		remoteUrl += "?" + urlParameter + "=" + targetUrl;
		remoteUrl += "&" + urlAuthority + "=" + secret;
		remoteUrl += "&" + urlTimestamp + "=" + timestamp;
		
		file.getResponse().sendRedirect(remoteUrl);
	}
	
	public void setDateFormatString(String dateFormatString) {
		this.dateFormatString = dateFormatString;
	}
	
	public void setFileLoadUrl(String fileLoadUrl) {
		this.fileLoadUrl = fileLoadUrl;
	}
	
	public void setFileOpenUrl(String fileOpenUrl) {
		this.fileOpenUrl = fileOpenUrl;
	}

	public void setServerHost(String serverHost) {
		this.serverHost = serverHost;
	}
}
